import Config from "@/_config/config.js";
// 公用方法
//加密需要crypto-js
const utils = {
  //格式化时间
  FormatTime(fmt, value) {
    let date;
    if (typeof value == "number") {
      date = new Date(value);
    } else {
      value = value.replace(/-/g, "/");
      date = new Date(value);
    }
    var o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
    return fmt;
  },
  /**
   * 读取身份证信息
   * @param {*} ic
   */
  getIdCardInfo(ic) {
    let sr =
      ic.substring(6, 10) +
      "-" +
      ic.substring(10, 12) +
      "-" +
      ic.substring(12, 14);
    let gender = ic.slice(14, 17) % 2 ? "男" : "女"; // 1代表男性，2代表女性
    return {
      birthday: sr,
      sex: gender
    };
  },
  /**
   * 根据日期返回年龄
   */
  getAgeToBirthday(birthday) {
    let age = 0;
    if (!birthday) return age;
    birthday = birthday.replace(/-/g, "/");
    let date = new Date(birthday);
    let yue = date.getFullYear() * 12 + date.getMonth() + 1;
    let date2 = new Date();
    let yue2 = date2.getFullYear() * 12 + date2.getMonth() + 1;
    age = Number.parseInt((yue2 - yue) / 12);
    //如果同月
    if (date.getMonth() + 1 == date2.getMonth() + 1) {
      //判断天数到没
      if (date.getDate() > date2.getDate()) {
        age--;
      }
    }
    return age;
  },
  /**
   * 将json 解析url 参数,数值类型进行加密
   * @param {*} json
   *  @param {*} isEncrypt 是否加密
   */
  JsonToUrl(json, isEncrypt = false) {
    let th = this;
    let result = "";
    for (let key in json) {
      let value = json[key];
      if (typeof value == "number" && isEncrypt == true) {
        value = th.stringToEncryption(value);
      }
      if (value !== "") {
        if (result == "") result = "?" + key + "=" + json[key];
        else result += "&" + key + "=" + json[key];
      }
    }
    return result;
  },
  /**判断对象是否加载完成 */
  isObject(obj, fn) {
    let t = setInterval(function () {
      if (window[obj]) {
        clearInterval(t);
        fn();
      }
    }, 300);
  },

  /**
   * 压缩图片
   * @param file 文件
   * @param basic 宽，高，压缩比率 ｛w,h,q｝q必传
   * @param fn 回调
   */
  gizpImg(file, basic, fn) {
    let g = path => {
      let img = new Image();
      img.src = path;
      img.onload = function () {
        let that = this;
        // 默认按比例压缩
        let w = basic.w || that.width,
          h = basic.h || that.height;
        //生成canvas
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        // 创建属性节点
        let anw = document.createAttribute("width");
        anw.nodeValue = w;
        let anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // q值越小，所绘制出的图像越模糊
        canvas.toBlob(
          function (bl) {
            fn(bl);
          },
          "image/jpeg",
          basic.q
        );
        // 回调函数返回base64的值
      };
    };
    this.fileToDataUrl(file, function (result) {
      g(result);
    });
  },
  /**
   * 事件节流
   * @param {*} method 调用方法
   * @param {*} delay  频率 毫秒(推荐100)
   * @param {*} duration 多少毫秒执行一次 毫秒
   * @param {*} isDefault 是否取消默认事件
   */
  throttle(method, delay, duration, isDefault = false) {
    let timer = null;
    let begin = new Date();
    return function (e) {
      let context = e,
        args = arguments;
      let current = new Date();
      if (isDefault) e.preventDefault();
      clearTimeout(timer);
      if (current - begin >= duration) {
        method.apply(context, args);
        begin = current;
      } else {
        timer = setTimeout(function () {
          method.apply(context, args);
        }, delay);
      }
    };
  },
  /**
   * 根据第一个json键合并第二个json(主要用来form表单赋值)
   * @param {*} one json 需要更改的json
   * @param {*} two  json  提供数据的json
   */
  joinFormJson(one, two) {
    let json = Object.assign({}, two);
    for (let key in one) {
      let value = json[key];
      if (value != undefined) one[key] = value;
    }
  },
  /**
   * 生成安全参数并签名
   * @param {*} par  需要传入url的参数(json)
   * @param {*} isEncrypt  是否number类型加密
   */
  createSafetyParam(par) {
    let th = this;
    par["signcode"] = this.analysisSafetyParam(par);
    return par;
  },
  /**
   * 验证安全参数
   * @param {*} par 需要验证的url的参数(json)
   */
  validSafetyParam(par) {
    let th = this;
    return new Promise(function (resolve, reject) {
      if (par.signcode) {
        let signcode = th.analysisSafetyParam(par);
        if (signcode == par.signcode) {
          resolve();
        } else {
          reject();
        }
      } else {
        reject();
      }
    });
  },
  analysisSafetyParam(par) {
    let th = this;
    let str = "";
    for (let item in par) {
      if (item != "signcode") str += par[item];
    }
    let signcode = hex_md5(str + Config.publicKey);
    return signcode;
  },
  /**
   * DES字符串加密
   */
  stringToEncryption(str) {
    let th = this;
    if (typeof str != "string") {
      str = str.toString();
    }
    let keyHex = CryptoJS.enc.Utf8.parse(Config.publicKey);
    let encrypted = CryptoJS.DES.encrypt(str, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString();
  },
  /**
   * DES字符串解密
   */
  stringToDecode(str) {
    let th = this;
    let keyHex = CryptoJS.enc.Utf8.parse(Config.publicKey);
    let decrypted = CryptoJS.DES.decrypt(
      {
        ciphertext: CryptoJS.enc.Hex.parse(str)
      },
      keyHex,
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      }
    );
    let result_value = decrypted.toString(CryptoJS.enc.Utf8);
    return result_value;
  },
  /** dataurl转blob*/
  dataURLToBlob(dataurl) {
    let arr = dataurl.split(",");
    let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  },
  //file转dataUrl
  fileToDataUrl(file, callBack) {
    let ready = new FileReader();
    /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
    ready.readAsDataURL(file);
    ready.onload = function () {
      callBack(this.result);
    };
  },
  //获取库存剩余数量-----2020.01.09--tl
  surplusDurg(obj, unitEnum) {
    let str = '';
    const fn = function (val) {
      let d = unitEnum.find(d2 => {
        return d2.id == val;
      });
      if (d) {
        return d.desc;
      } else {
        return "";
      }
    };
    const toUn = function (obj) {
      let str = "";
      if (typeof obj != "undefined") {
        str = obj;
      }
      return str;
    };
    if (obj.totalQuantity != undefined && obj.totalQuantityUnit != undefined) {
      if (obj.subsectionQuantity != undefined && obj.subsectionQuantity > 0) {
        str = `${toUn(obj.totalQuantity)}${fn(obj.totalQuantityUnit)}${toUn(obj.subsectionQuantity)}${fn(obj.subsectionQuantityUnit || "")}`;
      } else {
        str = `${toUn(obj.totalQuantity)}${fn(obj.totalQuantityUnit)}`;
      }
    } else {
      if (obj.residueNumSubsection > 0) {
        str = `${toUn(obj.residueNum)}${fn(obj.residueNumUnit)}${toUn(obj.residueNumSubsection)}${fn(obj.residueNumSubsectionUnit || "")}`;
      } else {
        str = `${toUn(obj.residueNum)}${fn(obj.residueNumUnit)}`;
      }
    }
    return str;
  },
  //获取单位---tl
  getDwByDwId(value, list) {
    let str = '';
    list.map(it => {
      if (it.id == value) {
        str = it.desc;
      }
    })
    return str;
  },
  //获取枚举值-tl
  getEunmValue(value, list) {
    let str = "";
    for (let key in list) {
      if (key == value) {
        str = list[key];
      }
    }
    return str;
  }
};
export default utils;
